<?php

namespace App\Jobs\Middleware;

use Illuminate\Support\Facades\Redis;

class RateLimited
{
    public function __construct()
    {
        // 如果是 book51 -> 1s => 并发量为 5
        // $this->allow = 5;
        // $this->every = 1;
    }

    /**
     * Process the queued job.
     * 限定每1秒钟只能处理5个任务
     * @param mixed    $job
     * @param callable $next
     * @return mixed
     */
    public function handle($job, $next)
    {
        Redis::throttle('key')
             ->block(0)->allow(5)
             ->every(1)
             ->then(function () use ($job, $next) {
                 // Lock obtained...

                 $next($job);
             }, function () use ($job) {
                 // Could not obtain lock...

                 $job->release(5);
             });
    }
}